//
//  GXDESTools.m
//  DESThreeTest
//
//  Created by huachun on 2019/2/12.
//  Copyright © 2019 zhang alan. All rights reserved.
//

#import "GXDESTools.h"
#import <CommonCrypto/CommonCrypto.h>
#import "GTMBase64.h"

//加密解密的key,与后台一致
#define USER_KEY  @"china108"
//初始化向量，与后台一致
#define initIv    @"jones728"

@implementation GXDESTools

+ (NSString *)encryptWithText:(NSString *)sText
{
    const void *vplainText;
    size_t plainTextBufferSize;
    NSData* data = [sText dataUsingEncoding:NSUTF8StringEncoding];
    plainTextBufferSize = [data length];
    vplainText = (const void *)[data bytes];
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    const void *vinitVec = (const void *) [initIv UTF8String];
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithmDES,
                       kCCOptionPKCS7Padding,
                       [USER_KEY UTF8String], //8位
                       kCCKeySizeDES,              //key的长度，8位
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    NSString *result;
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    result = [GTMBase64 stringByEncodingData:myData];
    return result;
}


@end
